import { _decorator, Component, game, Game, view, Font, resources,  } from 'cc';
const { ccclass, property } = _decorator;
import * as fgui from "fairygui-cc";
import WebSocketManager from './manager/WebSocketManager';

import BoomIndex from './BoomIndex'
import { ConfigModule } from './config/ConfigModule';
import { GameController } from './manager/GameController';
import EventDefine from './config/EventDefine';
import { URLParams } from './utils/URLParams';

@ccclass
export class main extends Component {

    private audioContext: any = null;

    @property(Font)
    troikaFont: Font = null;

    @property(Font)
    ruiziFont: Font = null;

    futuraFont: Font = null;

    onLoad(): void {
        game.frameRate = 60
        // screen.requestFullScreen()
        view.resizeWithBrowserSize(true)

        fgui.GRoot.create();

        // fgui.GRoot.inst.node.addComponent(SafeArea)
        // fgui.GRoot.inst.node.addComponent(Widget)
        // fgui.GRoot.inst.width = sys.getSafeAreaRect().width
        // fgui.GRoot.inst.height = sys.getSafeAreaRect().height

        fgui.UIPackage.loadPackage("UI/MainScene", this.onUILoaded.bind(this));

        game.on(Game.EVENT_HIDE, () => {
            console.log('game hide')
            GameController.Instance.eventTarget.emit(EventDefine.gameHide)
        }, this);

        game.on(Game.EVENT_SHOW, () => {
            console.log('game show')
            GameController.Instance.eventTarget.emit(EventDefine.gameShow)
            WebSocketManager.getInstance().connect();
        }, this);


        const loadTroika = new Promise<void>((resolve) => {
            resources.load('fonts/Troika', (error, data) => {
                if (!error) {
                    this.troikaFont = data;
                    fgui.registerFont('Troika', this.troikaFont);
                }
                resolve();
            });
        });

        const loadRuizi = new Promise<void>((resolve) => {
            resources.load('fonts/ruizi', (error, data) => {
                if (!error) {
                    this.ruiziFont = data;
                    fgui.registerFont('ruizi', this.ruiziFont);
                }
                resolve();
            });
        });

        const loadFutura = new Promise<void>((resolve) => {
            resources.load('fonts/Futura-Md-BT', (error, data) => {
                if (!error) {
                    this.futuraFont = data;
                    fgui.registerFont('Futura-Md-BT', this.futuraFont);
                }
                resolve();
            });
        });

        // 等待所有字体加载完成
        Promise.all([loadTroika, loadRuizi, loadFutura]).then(() => {
            console.log(`[${new Date().toLocaleTimeString()}]`, "加载字体完成 加载游戏内容");
        }).catch((err) => {
            console.error("加载字体失败:", err);
        });
    }

    onUILoaded() {
        this.addComponent(BoomIndex);
    }

    start() {
        console.log('onStart')
        let token = URLParams.getParam('token')
        const isTest = URLParams.getParam('test')

        // 根据是否有test参数设置token
        if (isTest) {
            GameController.Instance.token = token ?? ConfigModule.Test_Token
        } else {
            GameController.Instance.token = token
        }
        
        WebSocketManager.getInstance().connect();

        
        this.audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();

        // 创建隐藏的 AudioContext
        const ctx = new (window.AudioContext || (window as any).webkitAudioContext)();
        const source = ctx.createBufferSource();

        // 创建空音频缓冲
        const buffer = ctx.createBuffer(1, 1, 22050);
        source.buffer = buffer;

        // 连接并播放1ms后暂停
        source.connect(ctx.destination);
        source.start(0);
        source.stop(0.001);

        // 存储上下文供后续使用
        this.audioContext = ctx;
    }
}
